package org.example.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.exception.ServiceException;
import org.example.system.entity.Employee;
import org.example.system.entity.User;
import org.example.system.mapper.EmployeeMapper;
import org.example.system.mapper.UserMapper;
import org.example.system.service.AuthService;
import org.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 权限认证服务处实现
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 员工登录
     * @param loginEmployee
     * @return
     */
    @Override
    public String login(Employee loginEmployee) {
        //使用传入的用户名去数据库查找对应的记录
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,loginEmployee.getUsername());
        Employee existEmployee = employeeMapper.selectOne(wrapper);
        //如果用户不存在，提示用户名错误
        //如果用户存在，再去匹配密码，如果密码不匹配，提示密码错误
        if (existEmployee == null || !DigestUtil.bcryptCheck(loginEmployee.getPassword(),existEmployee.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }
        //生成token（JwtUtil）
        String key = existEmployee.getId() + "," + existEmployee.getUsername() + "," + UUID.randomUUID().toString();
        String token = JwtUtil.createToken(key);
        //把token放入redis缓存
        redisTemplate.opsForValue().set("LOGIN_EMPLOYEE_TOKEN:" + key,token,30, TimeUnit.MINUTES);
        //返回token
        return token;
    }

    /**
     * 用户登录
     * @param loginUser
     * @return
     */
    @Override
    public String login(User loginUser) {
        //使用传入的用户名去数据库查找对应的记录
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,loginUser.getUsername());
        User existUser = userMapper.selectOne(wrapper);
        //如果用户不存在，提示用户名错误
        //如果用户存在，再去匹配密码，如果密码不匹配，提示密码错误
        if (existUser == null || !DigestUtil.bcryptCheck(loginUser.getPassword(),existUser.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }
        //生成token（JwtUtil）
        String key = existUser.getId() + "," + existUser.getUsername() + "," + UUID.randomUUID().toString();
        String token = JwtUtil.createToken(key);
        //把token放入redis缓存
        redisTemplate.opsForValue().set("LOGIN_USER_TOKEN:" + key,token,7, TimeUnit.DAYS);
        //返回token
        return token;
    }

}
